package com.xingkeduo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingkeduo.AppPush;
import com.xingkeduo.dto.ResponseUtils;
import com.xingkeduo.dto.WebsocketMessageResponse;
import com.xingkeduo.pojo.query.ScreenMapper;
import com.xingkeduo.pojo.service.ScreenService;
import com.xingkeduo.pojo.table.Screen;
import com.xingkeduo.util.ScreenMapUtil;
import com.xingkeduo.util.pojo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import static com.xingkeduo.util.ScreenMapUtil.*;

/**
 * @author chi  2019-05-24 17:18
 **/
@RestController
@RequestMapping("/websocket/check")
@Slf4j
public class LoginController {

    @Resource
    private ScreenMapUtil screenMapUtil;

    @Resource
    private ScreenMapper screenMapper;
    @Resource
    private ScreenService screenService;

    @RequestMapping("")
    public ResponseEntity<ResponseUtils> login(String identificationCode, String storeId,String sign,String azNum, HttpServletRequest request) throws Exception{
        log.info("/websocket/check: storeId{}, identificationCode:{}, azNum:{}", storeId, identificationCode, azNum);
        if(StringUtils.isBlank(storeId)){
            throw new RuntimeException("未获取门店信息");
        }

        String token = request.getHeader("token");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("storeId",storeId);
        jsonObject.put("token",token);
        jsonObject.put("sign",sign);

        if(StringUtils.isBlank(azNum)){
            throw new BusinessException(BusinessException.Type.DEFAULT,"请更新客户端");
        }


        Screen screen = screenService.getBySimSerialNumber(azNum).orElseGet(Screen::new);
        screen.setStoreId(storeId);
        screen.setClientId(identificationCode);
        screen.setSimSerialNumber(azNum);
        screenService.insertOrUpdate(screen);


        screenMapUtil.loginSendMessage(identificationCode, new WebsocketMessageResponse<>(WebsocketMessageResponse.MessageTypeEnum.LOGIN, storeId, jsonObject));
        return new ResponseEntity<>(ResponseUtils.getSuccess(), HttpStatus.OK);
    }

    @RequestMapping("/info")
    public ResponseEntity<Object> login(String storeId) throws Exception{
        log.info("/websocket/check/info: storeId{}", storeId);
        if(StringUtils.isBlank(storeId)){
            return new ResponseEntity<>(JSON.toJSONString(STORE_LIST_MAP) + "       " + TRANS_SESSION_MAP.keySet() + "      " +  LOGIN_SESSION_MAP.keySet(), HttpStatus.OK);
        }
        Set<String> strings = STORE_LIST_MAP.get(storeId);
        return new ResponseEntity<>(strings, HttpStatus.OK);
    }


    //@Scheduled(fixedRate = 5 * 60 * 1000)
    public void reportCurrentTime() {
        log.info("发送心跳消息");
        if(STORE_LIST_MAP.size()>0){
            for (String storeId : STORE_LIST_MAP.keySet()) {
                WebsocketMessageResponse<String> websocketMessageResponse = new WebsocketMessageResponse<>(WebsocketMessageResponse.MessageTypeEnum.HEARTBEAT, storeId, "");
                screenMapUtil.transferSendMessage(websocketMessageResponse.getStoreId(), websocketMessageResponse);
            }
        }else {
            log.info("无店铺,不用发送心跳");
        }


        if(LOGIN_SESSION_MAP.size()>0){
            for (String s : LOGIN_SESSION_MAP.keySet()) {
                WebsocketMessageResponse<String> websocketMessageResponse = new WebsocketMessageResponse<>(WebsocketMessageResponse.MessageTypeEnum.HEARTBEAT, "", "");
                try {
                    LOGIN_SESSION_MAP.get(s).getBasicRemote().sendText(JSON.toJSONString(websocketMessageResponse));
                } catch (IOException e) {
                    log.error("{}", e);
                }
            }
        }
    }



    @Scheduled(cron="0 */5 * * * *")
    public void heartBeat() {
        log.info("发送五分钟心跳消息");
        WebsocketMessageResponse<Object> objectWebsocketMessageResponse = new WebsocketMessageResponse<>();
        objectWebsocketMessageResponse.setMessageTypeEnum(WebsocketMessageResponse.MessageTypeEnum.WORKPAD);

        List<Screen> screens = screenMapper.selectList(new QueryWrapper<Screen>().lambda().gt(Screen::getId, 0L));
        if(screens==null || screens.size()==0){
            return;
        }

        for (Screen screen : screens) {
            AppPush.pushMessage(screen.getClientId(), objectWebsocketMessageResponse);
        }

    }


    @RequestMapping("/heartBeat")
    public ResponseEntity<Object> heartBeat(String storeId) throws Exception{
        log.info("++++++++++");
        heartBeat();
        return new ResponseEntity<>("", HttpStatus.OK);
    }

}
